package cn.swing.his.passport.security.filter;

import cn.swing.his.common.exception.HisServiceException;
import cn.swing.his.common.pojo.domain.HisAuthenticationInfo;
import cn.swing.his.common.utils.JwtUtils;
import cn.swing.his.common.web.JsonResult;
import cn.swing.his.common.web.ResponseCode;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class SSOFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;
    @Value("${jwt.tokenHeader}")
    private String header;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        log.info("SSOFilter.doFilterInternal()");
        log.info("清除Spring Security上下文中的数据");
        SecurityContextHolder.clearContext();
        String jwt = request.getHeader(header);
        log.info("从请求头中获取到的jwt = {}",jwt);
        // 判断是否存在jwt数据
        if (!StringUtils.hasText(jwt)){
            log.info("请求头中无jwt数据,当前过滤器将放行");
            filterChain.doFilter(request,response);
            return;
        }
        log.info("请求头中存在jwt数据，将解析");
        // 解析jwt
        HisAuthenticationInfo doctorInfo = jwtUtils.parseJwt(jwt);
        UsernamePasswordAuthenticationToken authentication = null;
        if(doctorInfo != null){
//        try{
            List<String> authoritiesString = doctorInfo.getPermissions();
            List<GrantedAuthority> authorities = new ArrayList<>();
            for (String authorityValue : authoritiesString) {
                authorities.add(new SimpleGrantedAuthority(authorityValue));
            }
            authentication = new UsernamePasswordAuthenticationToken(
                    doctorInfo.getTelephone(),doctorInfo,authorities);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
//              throw new HisServiceException(ResponseCode.ERR_UNAUTHORIZED,"登录失败，请重新登录");
//            SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
            JsonResult<Void> jsonResult = JsonResult.failed(ResponseCode.ERR_UNAUTHORIZED,"登录失败，请重新登录");
            String jsonString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(jsonString);
        }
        // 放行
        filterChain.doFilter(request,response);
    }
}
